//
//  RHInvParamSelectView.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/6/14.
//

#import "RHInvParamSelectView.h"
#import "RHInvParamModel.h"
#import "SYChartTool.h"
#import "RHInvParamSelectCell.h"
#import "DeviceChartFieldModel.h"
#import "RHEndPointModel.h"

#define leftMargin 60
@interface RHInvParamSelectView ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, assign) NSInteger selectIndex;
//选择的单位
//@property (nonatomic, strong) NSMutableArray *selectUnitArr;
//选择的key
@property (nonatomic, strong) NSMutableArray *selectedArr;

@property (nonatomic ,strong) NSArray *modeArr;

@property (nonatomic ,strong) NSArray *selectKeys;//默认选中项

@property (nonatomic ,strong) UIView *grayView;

@property (nonatomic ,strong) UIView *selectView;

@property (nonatomic, strong) NSArray *params;//后台获取到的全部参数,包括数据点和曲线

@property (nonatomic, strong) NSArray *emuParams;//逆变器模块有部分电池参数是EMU端点的

@property (nonatomic, strong) RHEndPointModel *endpointModel;

@property (nonatomic, copy) NSString *deviceTypeCode;
@end

@implementation RHInvParamSelectView


-(instancetype)initWithEndpointModel:(RHEndPointModel *)endpointModel  allFieldParams:(NSArray*)params emuPrams:(NSArray*)emuParams deviceTypeCode:(NSString*)deviceTypeCode
{
    if (self = [super initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kUI_WINDOW_H)]) {
        _endpointModel = endpointModel;
        _params = params;
        _emuParams = emuParams;
        _deviceTypeCode = deviceTypeCode;
        self.selectedArr = [NSMutableArray array];
        self.selectIndex = 0;
        [self loadJsonFile];
        [self setupUI];
    }
    return self;
}
-(void)loadJsonFile{
    //移除之前选中的参数
    [self.selectedArr removeAllObjects];
    //日月元逆变器
    NSArray *selectKeys = @[@[@"Inv1_PVInVolt1",@"Inv1_PVInVolt2",@"Inv1_PVInCur1",@"Inv1_PVInCur2",@"Inv1_PVInPower1",@"Inv1_PVInPower2",@"Inv1_PVInPoTotal"],
    @[@"Inv1_ACInvoltR",@"Inv1_ACInvoltS",@"Inv1_ACInvoltT",@"Inv1_ACInAcPoR",@"Inv1_ACInAcPoS",@"Inv1_ACInAcPoT",@"Inv1_ACOutvoltR",@"Inv1_ACOutvoltS",@"Inv1_ACOutvoltT",@"Inv1_ACOutAcPoR",@"Inv1_ACOutAcPoS",@"Inv1_ACOutAcPoT",@"Inv1_ACOutAppPowR",@"Inv1_ACOutAppPowS",@"Inv1_ACOutAppPowT",@"Inv1_ACInAcPoTotal",@"Inv1_ACOutAcPoTotal",@"Inv1_ACOutAppTotPow",@"Inv1_ElectroToPower"],@[@"Emu_TV",@"Emu_Cur",@"Emu_BatSoc",@"Emu_HT"],@[@"Inv1_TotalEnerInTheD",@"Inv1_GridBuyDayEnergy",@"Inv1_GridSellDayEnergy",@"Inv1_ElectroDayEnergy",@"Emu_BCE_Day",@"Emu_BDE_Day"],@[]];
    NSString *file = @"he_para_select_inv_Other";
    
    if ([self.endpointModel.endpointCode isEqualToString:@"InvMegarevoLv"]) {//麦格瑞能逆变器
        selectKeys = @[@[@"Inv3_PVInV1",@"Inv3_PVInV2",@"Inv3_PVInV3",@"Inv3_PVInV4",@"Inv3_PVInCur1",@"Inv3_PVInCur2",@"Inv3_PVInCur3",@"Inv3_PVInCur4",@"Inv3_PVInPo1",@"Inv3_PVInPo2",@"Inv3_PVInPo3",@"Inv3_PVInPo4",@"Inv3_PVInPoTotal"],
        @[@"Inv3_GridVR",@"Inv3_GridVS",@"Inv3_GridVT",@"Inv3_GridPoR",@"Inv3_GridPoS",@"Inv3_GridPoT",@"Inv3_LoadVR",@"Inv3_LoadVS",@"Inv3_LoadVT",@"Inv3_LoadPoR",@"Inv3_LoadPoS",@"Inv3_LoadPoT",@"Inv3_GridAppPoR",@"Inv3_GridAppPoS",@"Inv3_GridAppPoT",@"Inv3_GridPoTotal",@"Inv3_LoadPoTotal",@"Inv3_GridAppTotPo",@"Inv3_HoLoPoTot"],@[@"Emu_TV",@"Emu_Cur",@"Emu_BatSoc",@"Emu_HT"],@[@"Inv3_TotalEnerInTheD",@"Inv3_GridBuyDayEnergy",@"Inv3_GridSellDayEnergy",@"Inv3_ElectroDayEnergy",@"Emu_BCE_Day",@"Emu_BDE_Day"],@[]];
        file = @"he_para_select_InvMegarevoLv_Other";
    }
    
    if([self.endpointModel.endpointCode isEqualToString:@"InvRenacHv"]){//纳通
        file  = @"he_para_select_InvRenacHv_Other";
        selectKeys = @[@[@"Inv2_Pv1Volt",@"Inv2_Pv2Volt",@"Inv2_Pv1Curr",@"Inv2_Pv2Curr",@"Inv2_Pv1Power",@"Inv2_Pv2Power"],
        @[@"Inv2_GridRVol",@"Inv2_GridSVol",@"Inv2_GridTVol",@"Inv2_InvRCur",@"Inv2_InvSCur",@"Inv2_InvTCur",@"Inv2_InvRPower",@"Inv2_InvSPower",@"Inv2_InvTPower",@"Inv2_EPSRVolt",@"Inv2_EPSSVolt",@"Inv2_EPSTVolt",@"Inv2_EPSRCurr",@"Inv2_EPSSCurr",@"Inv2_EPSTCurr",@"Inv2_EPSRPower",@"Inv2_EPSSPower",@"Inv2_EPSTPower",@"Inv2_GridPower",@"Inv2_Meter1TotalPower",@"Inv2_Meter2TotalPower",@"Inv2_Meter3TotalPower",@"Inv2_SysLoadPower"],@[@"Emu_TV",@"Emu_Cur",@"Emu_BatSoc",@"Emu_HT"],@[@"Inv2_TodayPVEnergy",@"Inv2_TodayChgEnergy",@"Inv2_TodayDhgEnergy",@"Inv2_TodayLoadEnergy",@"Emu_BCE_Day",@"Emu_BDE_Day"],@[]];
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"InvSolisLv"]) {//锦浪
        file = @"he_para_select_InvSolisLv_Other";
        selectKeys = @[@[@"Inv4_ABLineV",@"Inv4_BCLineV",@"Inv4_CALineV",@"Inv4_APhaC",@"Inv4_BPhaC",@"Inv4_CPhaC"],
        @[@"Inv4_DCV1",@"Inv4_DCV2",@"Inv4_DCV3",@"Inv4_DCV4",@"Inv4_DCC1",@"Inv4_DCC2",@"Inv4_DCC3",@""],@[@"Inv4_SmPtAACV",@"Inv4_SmPtBACV",@"Inv4_SmPtCACV",@"Inv4_SmPtAACC",@"Inv4_SmPtBACC",@"Inv4_SmPtCACC"],@[]];
    }

    if ([self.endpointModel.endpointCode isEqualToString:@"EMS"]) {
        file = @"he_para_select_ems_custom";
        selectKeys = @[@[@"Ems_BCE_Day",@"Ems_BDE_Day",@"Ems_PPG_Day",@"Ems_DGPE_Day",@"Ems_GGE_Day",@"Ems_GPE_Day",@"Ems_LE_Day"],@[@"Ems_BCE_Mon",@"Ems_BDE_Mon",@"Ems_PPG_Mon",@"Ems_DGPE_Mon",@"Ems_GGE_Mon",@"Ems_GPE_Mon",@"Ems_LE_Mon"],@[@"Ems_BCE_Year",@"Ems_BDE_Year",@"Ems_PPG_Year",@"Ems_DGPE_Year",@"Ems_GGE_Year",@"Ems_GPE_Year",@"Ems_LE_Year"],@[@"Ems_BCE_Ttl",@"Ems_BDE_Ttl",@"Ems_PPG_Ttl",@"Ems_DGPE_Ttl",@"Ems_GGE_Ttl",@"Ems_GPE_Ttl",@"Ems_LE_Ttl"],@[]];
    }
    
    //233k的使用EMU
    if ([self.endpointModel.endpointCode isEqualToString:@"EMU"]) {
        file = @"me_para_select_emu_custom";
        selectKeys = @[@[@"Emu_BCE_Day",@"Emu_BDE_Day"],@[]];
    }
    
    if ([self.endpointModel.endpointCode isEqualToString:@"Master"]) {
        file = @"he_para_select_master_custom";
        selectKeys = @[@[@"Mtr_Cur",@"Mtr_HT",@"Mtr_LT",@"Mtr_MaxPackDT",@"Mtr_Tmp_NTC2"],@[@"Mtr_HV",@"Mtr_LV",@"Mtr_MaxPackDV",@"Mtr_Cur"],@[@"Mtr_Cumtvchg",@"Mtr_CumtvDsg01"],@[]];
        //s40k 233k 主控有正负端口温度

        if ([self.deviceTypeCode isEqualToString:@"S40K LV1.0"]) {
            file = @"he_para_select_master_s40k_custom";
            selectKeys = @[@[@"Mtr_Cur",@"Mtr_HT",@"Mtr_LT",@"Mtr_MaxPackDT",@"Mtr_Tmp_NTC2",@"Mtr_DsgPort_P_Tem",@"Mtr_DsgProt_N_Tem"],@[@"Mtr_HV",@"Mtr_LV",@"Mtr_MaxPackDV",@"Mtr_Cur"],@[@"Mtr_Cumtvchg",@"Mtr_CumtvDsg01"],@[]];
            
        }
        if ([self.deviceTypeCode is233DeviceType]) {
            file = @"me_para_select_master_233_custom";//个别参数位置调换了一下
            selectKeys = @[@[@"Mtr_HT",@"Mtr_LT",@"Mtr_DsgPort_P_Tem",@"Mtr_DsgProt_N_Tem"],@[@"Mtr_TV",@"Mtr_HExtVolt",@"Mtr_HV",@"Mtr_LV",@"Mtr_MaxPackDV"],@[@"Mtr_CumtvChg01",@"Mtr_CumtvDsg01"],@[]];//Mtr_Cumtvchg这个不一样
        }
        if ([self.deviceTypeCode is61DeviceType]) {
            file = @"he_para_select_master_61k_custom";//个别参数位置调换了一下
            selectKeys = @[@[@"Mtr_Cur",@"Mtr_HT",@"Mtr_LT",@"Mtr_MaxPackDT"],@[@"Mtr_HV",@"Mtr_LV",@"Mtr_MaxPackDV",@"Mtr_Cur"],@[@"Mtr_CumtvDsg01"],@[]];
        }
        //纳通高压
        if ([self.deviceTypeCode isHVDeviceType]) {
            file = @"he_para_select_master_nt_custom";
            selectKeys = @[@[@"Mtr_Cur",@"Mtr_HT",@"Mtr_LT",@"Mtr_Tmp_NTC2"],@[@"Mtr_HV",@"Mtr_LV",@"Mtr_MaxPackDV",@"Mtr_Cur"],@[@"Mtr_Cumtvchg",@"Mtr_CumtvDsg01"],@[]];
        }
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"Pack"]) {
        file = @"he_para_select_custom";
        selectKeys = @[@[@"Pck_Cur",@"Pck_HT",@"Pck_LT",@"Pck_Tmp_Mos",@"Pck_Tmp_Cnct",@"Pck_NegTemp",@"Pck_TempDiff"],@[@"Pck_HV",@"Pck_LV",@"Pck_Cur",@"Pck_VoltDiff"],@[@"Pck_CumtvChg1",@"Pck_CumtvDsg1"],@[]];
        if ([self.deviceTypeCode is233DeviceType]||
            [self.deviceTypeCode is61DeviceType]) {
            file = @"me_para_select_pack_233_custom";
            //没有了能量分析
            selectKeys = @[@[@"Pck_Cur",@"Pck_HT",@"Pck_LT",@"Pck_Tmp_Mos",@"Pck_Tmp_Cnct",@"Pck_NegTemp",@"Pck_TempDiff"],@[@"Pck_HV",@"Pck_LV",@"Pck_Cur",@"Pck_VoltDiff"],@[]];
        }

        if ([self.deviceTypeCode isHVDeviceType]) {//纳通高压
            //曲线参数去掉一些参数,纳通的没那么多,没有能量分析
            file = @"he_para_select_pack_RenacHv_custom";
            selectKeys = @[@[@"Pck_Cur",@"Pck_HT",@"Pck_LT",@"Pck_Tmp_Mos",@"Pck_Tmp_Cnct",@"Pck_NegTemp",@"Pck_TempDiff"],@[@"Pck_HV",@"Pck_LV",@"Pck_Cur",@"Pck_VoltDiff"],@[]];
        }
        if ([self.deviceTypeCode isEqualToString:@"S40K LV1.0"]) {//s40K 迈格瑞能
            file = @"he_para_select_pack_InvMegarevoLv_custom";
            selectKeys = @[@[@"Pck_Cur",@"Pck_HT",@"Pck_LT",@"Pck_Tmp_Mos",@"Pck_Tmp_Cnct",@"Pck_NegTemp",@"Pck_TempDiff"],@[@"Pck_HV",@"Pck_LV",@"Pck_Cur",@"Pck_VoltDiff"],@[@"Pck_CumtvChg1",@"Pck_CumtvDsg1"],@[]];
        }
        if ([self.deviceTypeCode isXStack]) {
            //储充一体取消数据点Mos温度（Pck_Tmp_Mos）、正/负极连接器温度（Pck_Tmp_Cnct、Pck_NegTemp）
            file = @"he_para_select_pack_xstack_custom";
        }
    }
    if([self.endpointModel.endpointCode isEqualToString:@"PcsKH"]||
       [self.endpointModel.endpointCode isEqualToString:@"PcsTQ"]||
       [self.endpointModel.endpointCode isEqualToString:@"PcsJL"]){//61度电天青和锦浪暂时没有曲线
        file  = @"me_para_select_pcs_Other";
        selectKeys = @[
        @[@"PcsKH_SystemApparentPower", @"PcsKH_SystemActivePower",@"PcsKH_SystemReactivePower"],
        @[@"PcsKH_SystemOutput_U_Current",@"PcsKH_SystemOutput_V_Current",@"PcsKH_SystemOutput_W_Current"],
        @[]];
    }
    
    if([self.endpointModel.endpointCode isEqualToString:@"PcsSA"]){//61度电天青和锦浪暂时没有曲线
        file  = @"he_para_select_pcs_Solark_Other";
        selectKeys = @[
        @[@"PcsSA_Battery_Charge_Energy_Today", @"PcsSA_Battery_Discharge_Energy_Today",@"PcsSA_Historical_Battery_Charge_Energy",@"PcsSA_Historical_Battery_Discharge_Energy"],
        @[@"PcsSA_Load_Phase_A_Voltage",@"PcsSA_Load_Phase_B_Voltage",@"PcsSA_Load_Phase_C_Voltage",@"PcsSA_Load_Side_Total_Active_Power",@"PcsSA_Load_Energy_Consumption_Today",@"PcsSA_Historical_Load_Energy_Consumption"],
        @[@"PcsSA_PV1_Input_Power",@"PcsSA_PV2_Input_Power",@"PcsSA_PV3_Input_Power",@"PcsSA_PV4_Input_Power",@"PcsSA_Total_PV_Power",@"PcsSA_PV_Energy_Generated_Today",@"PcsSA_Historical_PV_Power_Generated"],
        @[@"PcsSA_Grid_Phase_A_Voltage",@"PcsSA_Grid_Phase_B_Voltage",@"PcsSA_Grid_Phase_C_Voltage",@"PcsSA_Grid_Side_Total_Power",@"PcsSA_Grid_Energy_Imported_Today",@"PcsSA_Grid_Energy_Exported_Today",@"PcsSA_Historical_Grid_Import_Energy",@"PcsSA_Historical_Grid_Sell_Energy"],
        @[@"PcsSA_Gen_Side_Phase_A_Voltage",@"PcsSA_Gen_Side_Phase_B_Voltage",@"PcsSA_Gen_Side_Phase_C_Voltage",@"PcsSA_Gen_Side_Total_Active_Power",@"PcsSA_Generator_Energy_Today",@"PcsSA_Total_Generator_Output_Energy"],
        @[]];
    }
    
    if([self.endpointModel.endpointCode isEqualToString:@"PcsYT"]){//233欧规
        file  = @"me_para_select_pcs_EU_custom";
        selectKeys = @[
        @[@"PcsYT_SysAcABVaildVol", @"PcsYT_SysAcBCVaildVol",@"PcsYT_SysAcCAVaildVol",@"PcsYT_SysAcVolFreq"],
        @[@"PcsYT_SysAcAVaildElect",@"PcsYT_SysAcBVaildElect",@"PcsYT_SysAcCVaildElect"],
        @[@"PcsYT_SysAcOutApparentPwr",@"PcsYT_SysAcOutActivePwr",@"PcsYT_SysAcOutReactivePwr"],
        @[]];
    }
    if([self.endpointModel.endpointCode isEqualToString:@"LCU"]){
        file  = @"me_para_select_lcu_233_custom";
        selectKeys = @[@[@"Lci_i16outTemp", @"Lci_i16retTemp",@"Lci_i16exhTemp",@"Lci_i16ambTemp",@"Lci_u16pumpSpeed"],@[]];
    }
    if([self.endpointModel.endpointCode isEqualToString:@"DHM"]){
        file  = @"me_para_select_dehum_233_custom";
        selectKeys = @[@[@"dehum_InterTemprtVal", @"dehum_EnvirTemprtVal",@"dehum_ENvirHumVal"],@[]];
    }
    
    if([self.endpointModel.endpointCode isEqualToString:@"MTR"]){
        file  = @"me_para_select_meter_233_custom";
        selectKeys = @[@[@"GrSmmtr_ABLneVolt", @"GrSmmtr_CBLneVolt",@"GrSmmtr_ACLneVolt"],@[@"GrSmmtr_TotlActivePower"],@[@"GrSmmtr_CurrFwdActEng",@"GrSmmtr_CurrRevActEng"],@[]];
    }
    if([self.endpointModel.endpointCode isEqualToString:@"BCU"]){
        file  = @"he_para_select_bcu_215_EU_custom";
        selectKeys = @[@[@"BCU_Voltage", @"BCU_Current",@"BCU_Cumulative_charging_energy",@"BCU_Cumulative_discharging_energy",@"BCU_SOC"],@[]];
    }
    
    //储充一体
    if([self.endpointModel.endpointCode isEqualToString:@"DCDC"]){
        file  = @"he_para_select_dcdc_xstack_custom";
        selectKeys = @[@[@"XDc_BusVol", @"XDc_BusDischgCur",@"XDc_BusDischgPwr", @"XDc_BusChgCur",@"XDc_BusChgPwr"],@[@"XDc_BatVol",@"XDc_BatDischgCur", @"XDc_BatDischgPwr",@"XDc_BatChgCur",@"XDc_BatChgPwr"],@[]];
    }
    //储充一体
    if([self.endpointModel.endpointCode isEqualToString:@"InvHISOLAR"]){
        file  = @"he_para_select_inv_xstack_custom";
        selectKeys = @[@[@"Inv5_GridVR", @"Inv5_GridVS",@"Inv5_GridCR", @"Inv5_GridCS",@"Inv5_GridPR",@"Inv5_GridPS", @"Inv5_GridPwr"],@[@"Inv5_GenVR",@"Inv5_GenVS", @"Inv5_GenCR",@"Inv5_GenCS",@"Inv5_GenPR",@"Inv5_GenPS", @"Inv5_GenPwr"],@[@"Inv5_LoadVR",@"Inv5_LoadVS", @"Inv5_LoadPR",@"Inv5_LoadPS",@"Inv5_LoadPwr"],@[@"Inv5_InvVR",@"Inv5_InvVS", @"Inv5_InvCR",@"Inv5_InvCS",@"Inv5_InvPR",@"Inv5_InvPS", @"Inv5_InvPwr"],@[@"Inv5_MeterVR",@"Inv5_MeterVS", @"Inv5_MeterPR",@"Inv5_MeterPS",@"Inv5_MeterPwr",@"Inv5_CTCR",@"Inv5_CTCS"],@[@"Inv5_PVV1",@"Inv5_PVV2",@"Inv5_PVV3",@"Inv5_PVC1",@"Inv5_PVC2",@"Inv5_PVC3",@"Inv5_PVP1",@"Inv5_PVP2",@"Inv5_PVP3"],@[]];
    }
    
    NSArray *jsonArr = [SYChartTool loadJsonFileWithName:file];
    self.dataArray = [NSArray yy_modelArrayWithClass:[RHInvParamModel class] json:jsonArr];
    
    
    
    
    //设置选中项选中项
    NSArray *keyArr = selectKeys[self.selectIndex];
    [keyArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dataArray enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull cellModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [cellModel.rowArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [rowModel.itemArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([itemModel.keyCode isEqualToString:key]) {
                        itemModel.isSelected = YES;
                        [self.selectedArr addObject:itemModel];
                    }
                }];
            }];
        }];
    }];
    
    [self resetKeyNameAndUnit];
    
    [self.tableView reloadData];
}

#pragma mark ------- 使用后台的keyname 和 unit

-(void)resetKeyNameAndUnit
{
    //重置单位和keyName 不用json文件里的
    [self.dataArray enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull cellModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [cellModel.rowArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [rowModel.itemArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                if (itemModel.useLocalName) {
                    return;
                }
                itemModel.keyName = @"--";
                itemModel.unit = @"--";
            }];
        }];
    }];
    
    //匹配当前端点类型参数的单位和keyName
    [self.params enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull fieldModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dataArray enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull cellModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [cellModel.rowArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [rowModel.itemArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
            
                    if ([itemModel.keyCode isEqualToString:fieldModel.keyCode]) {
                        if (itemModel.useLocalName) {
                            return;//使用本地配置的参数名
                        }
                        itemModel.unit = fieldModel.unitName;
                        itemModel.keyName = fieldModel.keyName;
                    }
                }];
            }];
        }];
    }];
    
    //匹配emu端点类型参数的单位和keyName
    [self.emuParams enumerateObjectsUsingBlock:^(DeviceChartFieldModel*  _Nonnull emuModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dataArray enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull cellModel, NSUInteger idx, BOOL * _Nonnull stop) {
            [cellModel.rowArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
                [rowModel.itemArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (itemModel.useLocalName) {
                        return;//使用本地配置的参数名
                    }
                    if ([itemModel.keyCode isEqualToString:emuModel.keyCode]) {
                        itemModel.unit = emuModel.unitName;
                        itemModel.keyName = emuModel.keyName;
                    }
                }];
            }];
        }];
    }];
}


-(void)setupUI
{
    if ([self.endpointModel.endpointCode isEqualToString:@"InvVoltronicLv"]||
        [self.endpointModel.endpointCode isEqualToString:@"InvMegarevoLv"]||
        [self.endpointModel.endpointCode isEqualToString:@"InvRenacHv"]) {
        self.modeArr = @[@"光伏分析",@"交流分析",@"电池分析",@"能量分析",@"自定义"];
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"InvSolisLv"]) {//锦浪
        self.modeArr = @[@"电网分析",@"光伏分析",@"智能端口分析",@"自定义"];
    }

    if ([self.endpointModel.endpointCode isEqualToString:@"PcsKH"]||
        [self.endpointModel.endpointCode isEqualToString:@"PcsTQ"]) {
        self.modeArr = @[@"功率分析",@"交流分析",@"自定义"];
    }
    
    if ([self.endpointModel.endpointCode isEqualToString:@"PcsSA"]) {
        self.modeArr = @[@"电池分析",@"负载分析",@"光伏分析",@"电网分析",@"发电机分析",@"自定义"];
    }
    
    if ([self.endpointModel.endpointCode isEqualToString:@"PcsYT"]) {
        self.modeArr = @[@"电压分析",@"电流分析",@"功率分析",@"自定义"];
    }
   
    if ([self.endpointModel.endpointCode isEqualToString:@"EMS"]||
        [self.endpointModel.endpointCode isEqualToString:@"EMU"]) {
        self.modeArr = @[@"电量日分析",@"电量月分析",@"电量年分析",@"电量累计分析",@"自定义"];
        if ([self.deviceTypeCode is233DeviceType]) {
            self.modeArr = @[@"电量日分析",@"自定义"];
        }
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"Master"]) {
        self.modeArr = @[@"温度分析",@"电压分析",@"能量分析",@"自定义"];
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"Pack"]) {
        self.modeArr = @[@"温度分析",@"电压分析",@"能量分析",@"自定义"];
        if ([self.deviceTypeCode is233DeviceType]||
            [self.deviceTypeCode is61DeviceType]) {
            self.modeArr = @[@"温度分析",@"电压分析",@"自定义"];
        }
        if ([self.deviceTypeCode isHVDeviceType]) {//纳通高压
            //曲线参数去掉一些参数,纳通的没那么多
            self.modeArr = @[@"温度分析",@"电压分析",@"自定义"];
        }
    }
    if ([self.endpointModel.endpointCode isEqualToString:@"LCU"]||
        [self.endpointModel.endpointCode isEqualToString:@"DHM"]) {
        self.modeArr = @[@"温度分析",@"自定义"];
    }
    
    if ([self.endpointModel.endpointCode isEqualToString:@"MTR"]) {
        self.modeArr = @[@"电压分析",@"功率分析",@"能量分析",@"自定义"];
    }
    
    if ([self.endpointModel.endpointCode isEqualToString:@"BCU"]) {
        self.modeArr = @[@"能量分析",@"自定义"];
    }
    //储充一体
    if ([self.endpointModel.endpointCode isEqualToString:@"DCDC"]) {
        self.modeArr = @[@"高压侧分析",@"电池侧分析",@"自定义"];
    }
    //储充一体
    if ([self.endpointModel.endpointCode isEqualToString:@"InvHISOLAR"]) {
        self.modeArr = @[@"电网分析",@"油机分析",@"负载分析",@"逆变分析",@"电表分析",@"光伏分析",@"自定义"];
    }
    _grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kUI_WINDOW_H)];
    _grayView.backgroundColor = UIColor.whiteColor;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(diss)];
    [_grayView addGestureRecognizer:tap];
    
    [self addSubview:_grayView];
    _selectView = [[UIView alloc]initWithFrame:CGRectMake(kUI_WINDOW_W, 0, kUI_WINDOW_W - leftMargin, kUI_WINDOW_H)];
    _selectView.backgroundColor = kCOLOR_HEX(@"#F4F6F9");
    [self addSubview:_selectView];
    
    
   
    
    QMUILabel *titleLab =  [QMUILabel labelWithFont:kBOLDSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#3F4443") textAligment:NSTextAlignmentLeft];
    titleLab.backgroundColor = UIColor.whiteColor;
    titleLab.text = [NSString stringWithFormat:@"      %@",@"推荐分析".rh_localized];
   
    NSInteger rowCount = self.modeArr.count%2?self.modeArr.count/2+1:self.modeArr.count/2;
    CGFloat optionViewHeight = 35*rowCount +(rowCount-1)*15 + 30;
    UIView *optionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, optionViewHeight)];
    optionView.backgroundColor = kCOLOR_HEX(@"#F4F6F9");
  
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W - leftMargin, 45+optionView.height + (kSafe_top>0?kSafe_top:15))];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView addSubview:titleLab];
    [headerView addSubview:optionView];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(kSafe_top);
        make.left.right.mas_offset(0);
        make.height.offset(45);
    }];
    
    [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(titleLab.mas_bottom);
        make.height.offset(optionViewHeight);
    }];
//    UIScrollView *scrollView = [[UIScrollView alloc]init];
//    scrollView.showsHorizontalScrollIndicator = NO;
//    scrollView.contentInset = UIEdgeInsetsMake(0, 15, 0, 15);
//    [topView addSubview:scrollView];
//    UIView *scrollContentView = kView;
//    [scrollView addSubview:scrollContentView];
//    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.insets(UIEdgeInsetsZero);
//    }];
//    [scrollContentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.insets(UIEdgeInsetsZero);
//        make.width.equalTo(scrollView);
//    }];
    

    CGFloat itemWidth = (kUI_WINDOW_W - 45 - leftMargin)/2;
    __block QMUIButton *lastItem;
    [self.modeArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *btn = [[QMUIButton alloc]init];
        [btn setTitle:obj.rh_localized forState:UIControlStateNormal];
        btn.titleLabel.font = kSYSTEMFONT(14);
        [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.8] forState:UIControlStateNormal];
        btn.backgroundColor = kCOLOR_HEX(@"F6F8FA");
        btn.layer.cornerRadius = 8;
        btn.userInteractionEnabled = YES;
        [btn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"FFFFFF"),kCOLOR_HEX(@"FFFFFF")] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
        [optionView addSubview:btn];
       
//        CGFloat btnWidth = [obj getStringWidthFont:btn.titleLabel.font limitHeight:30] +40;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            
            if(lastItem){
                //换行
                if (idx % 2 == 0) {
                    make.left.mas_offset(15);
                    make.top.equalTo(lastItem.mas_bottom).offset(15);
                    make.size.equalTo(lastItem);
                }else{
                    make.left.equalTo(lastItem.mas_right).offset(15);
                    make.size.centerY.equalTo(lastItem);
                }
                
            }else{
                //第一个
                make.left.mas_offset(15);
                make.height.offset(35);
                make.width.offset(itemWidth);
                make.top.mas_offset(15);
            }
        }];
        //最后一个
        if(idx == self.modeArr.count-1){
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.mas_offset(-15);
            }];
        }
        lastItem = btn;
        kWeakSelf;
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.selectIndex = idx;
            [weakSelf loadJsonFile];
            
        }];
        
        [RACObserve(self, selectIndex) subscribeNext:^(id  _Nullable x) {
            if([x integerValue] == idx){
                [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                [btn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"#05C79D"),kCOLOR_HEX(@"#05C79D")] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
                [btn rounded:8 width:1 color:kCOLOR_HEX(@"#05C79D")];
            }else{
                [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                [btn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"FFFFFF"),kCOLOR_HEX(@"FFFFFF")] locations:@[@(0),@(1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5)];
                [btn rounded:8 width:1 color:kCOLOR_HEX(@"#E3E6ED")];
            }
        }];
   
    }];
    
    UIView *bottomView = kView;
    bottomView.backgroundColor = UIColor.whiteColor;
    [_selectView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.height.offset(44+15+(kSafe_bottom>0?kSafe_bottom:15));
    }];
    
    QMUIButton *cancelBtn = [[QMUIButton alloc]init];
    [cancelBtn setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = kSYSTEMFONT(16);
    [cancelBtn setTitleColor:kCOLOR_HEX(@"#CCCCCC") forState:UIControlStateNormal];
    [cancelBtn setQmui_borderColor:kCOLOR_HEX(@"#CCCCCC")];
    [cancelBtn setQmui_borderWidth:1];
    [cancelBtn setQmui_borderPosition:QMUIViewBorderPositionTop|QMUIViewBorderPositionLeft|QMUIViewBorderPositionRight|QMUIViewBorderPositionBottom];
    [cancelBtn setBackgroundColor:UIColor.whiteColor];
    [cancelBtn setCornerRadius:8];
    [bottomView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.left.mas_offset(15);
        make.height.offset(44);
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(16);
    [sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [sureBtn setGradientBackgroundWithColors:@[kCOLOR_HEX(@"#05C79D"),kCOLOR_HEX(@"#05C79D")] orientation:GradientOrientationLeftToRight];
    [sureBtn setCornerRadius:8];
    [bottomView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(15);
        make.right.mas_offset(-15);
        make.left.equalTo(cancelBtn.mas_right).mas_offset(15);
        make.width.height.equalTo(cancelBtn);
    }];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 40) style:UITableViewStylePlain];
    _tableView.backgroundColor = kCOLOR_HEX(@"#F4F6F9");
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = headerView;
    [_selectView addSubview:_tableView];
   
    [_tableView registerClass:[RHInvParamSelectCell class] forCellReuseIdentifier:@"RHInvParamSelectCell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.left.right.mas_offset(0);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    kWeakSelf;
    [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf diss];
    }];
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf sureAction];
    }];
}

-(void)sureAction
{
    if (self.selectBlock) {
        self.selectBlock(self.selectedArr.copy);
//        //自定义模式
//        if (self.selectIndex == (self.modeArr.count-1)) {
//            self.selectBlock(self.selectedArr.copy);
//        }else{
//            //其他默认模式,找出默认选择的参数
//            NSMutableArray *mtbArr = [NSMutableArray array];
//            [self.dataArray enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                [obj.rowArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull rowObj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    [rowObj.itemArr enumerateObjectsUsingBlock:^(RHInvParamModel * _Nonnull itemObj, NSUInteger idx, BOOL * _Nonnull stop) {
//                        if (itemObj.isSelected) {
//                            [mtbArr addObject:itemObj];
//                        }
//                    }];
//                }];
//            }];
//            self.selectBlock(mtbArr.copy);
//        }
        NSLog(@"---------->选择了%ld个参数:%@",self.selectedArr.count,self.selectedArr);
    }
    [self diss];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    RHInvParamSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHInvParamSelectCell"];
    
    cell.cellModel = self.dataArray[indexPath.row];
    kWeakSelf;
    cell.selectBlock = ^(RHInvParamModel * _Nonnull model) {
        if (weakSelf.selectIndex == (weakSelf.modeArr.count-1)) {
           
            //自定义只能选择两个单位
            if (!model.isSelected ) {
               
                if ([weakSelf canAddModel:model]) {
                    model.isSelected = !model.isSelected;
                    [weakSelf.selectedArr addObject:model];
                    [weakSelf.tableView reloadData];
                }
               
            }else{
                //取消
                model.isSelected = !model.isSelected;
                [weakSelf.selectedArr removeObject:model];
                [weakSelf.tableView reloadData];
            }
            
        }else{
            [QMUITips showInfo:@"只有自定义时才可以选择".rh_localized];
        }
    };
    return cell;
}

-(BOOL)canAddModel:(RHInvParamModel*)model
{
    if (self.selectedArr.count >= 10) {
        [QMUITips showInfo:@"最多只能添加10个参数!".rh_localized];
        return NO;
    }
    NSMutableArray *unitArr = [NSMutableArray array];
    [self.selectedArr enumerateObjectsUsingBlock:^(RHInvParamModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![unitArr containsObject:obj.unit]) {
            [unitArr addObject:obj.unit];
        }
    }];
    //包含这个单位
    if ([unitArr containsObject:model.unit]) {
        return YES;
    }else{
        //不包含,最多4个单位
        if(unitArr.count<4){
            return YES;
        }else{
            [QMUITips showInfo:[NSString stringWithFormat:@"最多只能添加%@个单位!".rh_localized,@"4"]];
            return NO;
        }
    }
    
}

-(void)showInWindowAnimate
{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    self.grayView.backgroundColor = kCOLOR_HEX_A(@"000000", 0);
    self.selectView.x = kUI_WINDOW_W;
    [UIView animateWithDuration:0.3 animations:^{
        self.grayView.backgroundColor = kCOLOR_HEX_A(@"000000", 0.4);
        self.selectView.x = leftMargin;
    }];
}

-(void)diss
{
    [UIView animateWithDuration:0.3 animations:^{
            self.grayView.backgroundColor = kCOLOR_HEX_A(@"000000", 0);
            self.selectView.x = kUI_WINDOW_W;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
}
@end
